<?php

namespace App\Console\Tools\Clean;

use Helper\Timed;
use Illuminate\Console\Command;
use App\Models\Elasticsearch\Log\Cost as LogCost;
use App\Models\Elasticsearch\Log\Login as LogLogin;
use App\Models\Elasticsearch\Settlement\Info as SettlementInfo;
use App\Models\Elasticsearch\Settlement\Detail as SettlementDetail;
use App\Models\Elasticsearch\Order\Wallet as WalletOrder;

class Elasticsearch extends Command
{
    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'tools:clean:es {--days=90}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '【工具】清理 Elasticsearch 数据';

    /**
     * 创建命令
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 执行命令
     *
     * @return mixed
     */
    public function handle()
    {
        if (!config('elasticsearch.default')) {
            $this->error('不是 Elasticsearch 环境');
            return;
        }

        // 参数天数
        $days = $this->option('days');
        if ($days < 60) {
            $this->error('天数必须大于60天之前');
            return;
        }

        // 删除结束时间 (不包含当前天)
        $timedEnd = Timed::getDayCurrentTimed(time() - 86400 * $days);

        // 查询数据删除的开始时间
        $params['body']['aggs']['end_time']['min'] = [
            'field' => 'end_time'
        ];
        $result = SettlementInfo::search($params);

        // 找不到数据，直接结束
        if (empty($timedStart = $result['aggregations']['end_time']['value'])) {
            $this->info('没有需要删除的数据');
            return;
        }

        // 删除开始时间 (包含当前天)
        $timedStart = Timed::getDayCurrentTimed($timedStart);

        // 开始时间大于等于结束时间，直接结束
        if ($timedStart >= $timedEnd) {
            $this->info('没有需要删除的数据');
            return;
        }

        // 输出提示【任务时间】
        $this->info($this->description . date('Y-m-d', $timedStart) . '~' . date('Y-m-d', $timedEnd));

        // 索引列表
        $indices = [];
        for ($timed = $timedStart; $timed < $timedEnd; $timed += 86400) {
            $day = date('Y.m.d', $timed);

            $indices[] = LogCost::INDEX_NAME . '-' . $day;
            $indices[] = LogLogin::INDEX_NAME . '-' . $day;

            $indices[] = SettlementInfo::INDEX_NAME . '-' . $day;

            $indices[] = SettlementDetail::INDEX_NAME . '_slo-' . $day;
            $indices[] = SettlementDetail::INDEX_NAME . '_fish-' . $day;

            $indices[] = WalletOrder::INDEX_NAME . '-' . $day;
        }

        // dd($indices);

        $client = SettlementInfo::client()->indices();
        // 删除索引 (每次100条)
        for ($offset = 0; $offset < count($indices); $offset += 100) {
            $client->delete([
                'index' => array_slice($indices, $offset, 100),
                // 忽略无效索引
                'ignore_unavailable' => true,
            ]);
        }

        $this->info('数据删除完成');
    }
}
